import * as webpack from "webpack";

import commonConfig from "./webpack.common";

const path = require("path");
const { merge } = require("webpack-merge");
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const isAnalyze = process.env.ANALYZE === "1";

const config: webpack.Configuration = merge(commonConfig, {
  mode: "production",
  // 不生成source-map
  devtool: false,
  output: {
    filename: "[name].[contenthash].bundle.js",
    path: path.resolve(process.cwd(), "dist"),
    clean: true,
  },
  plugins: [
    // 分析打包结果
    isAnalyze && new BundleAnalyzerPlugin(),
    // 单独提取css
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css",
    }),
  ],
  optimization: {
    // 单独提取运行时模块
    runtimeChunk: true,
    // 压缩代码
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true,
      }),
    ],
    // 单独提取公共模块
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
  },
});

export default config;
